package org.sensation.file.channel;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class SetupToWriteTempFile{
	private static final int DEFAULT_INIT_FILE_SIZE = 1024 * 10000;
	protected File file;
	protected FileChannel targetChannel;
	
	public SetupToWriteTempFile(String targetFilePath, int targetFileSize) throws FileNotFoundException, IOException {
		super();
		this.file = new File(targetFilePath);
		initTargetFile(targetFileSize);
	}
	
	private void initTargetFile(int targetFileSize) throws FileNotFoundException, IOException {
		FileOutputStream fos = new FileOutputStream(file);
		FileChannel channel = fos.getChannel();
		int size = checkLowBufferSize(targetFileSize);
		int offset = 0;
		int lastIndex = targetFileSize / size;
		int remainder = targetFileSize % size;
		
		ByteBuffer buffer = ByteBuffer.allocate(size);
		for (int index=0; index < lastIndex; index++)
			offset = writeAndNextOffset(channel, size, offset, buffer);
		remainderWrite(channel, offset, remainder);
		
		channel.close();
	}
	
	private int writeAndNextOffset(FileChannel channel, int size, int offset,
			ByteBuffer buffer) throws IOException {
		channel.write(buffer,offset);
		offset = offset + size;
		return offset;
	}
	
	private void remainderWrite(FileChannel channel, int offset, int remainder)
			throws IOException {
		ByteBuffer remainderBuffer = ByteBuffer.allocate(remainder);
		channel.write(remainderBuffer, offset);
	}

	private int checkLowBufferSize(int targetFileSize) {
		int size = DEFAULT_INIT_FILE_SIZE;
		if (size > targetFileSize) {
			size = targetFileSize;
		}
		return size;
	}
	
	public File getFile() {
		return file;
	}

	public void close() throws IOException{
		if(targetChannel != null){
			try {
				targetChannel.close();
			} catch (Exception e) {
				targetChannel.close();
			}
		}
	}
}
